<?php

/**
 * Created by PhpStorm.
 * User: dev
 * Date: 27/10/14
 * Time: 2:05 PM
 */
use Laravel\Redirect;

class Member_Post_Controller extends Base_Controller
{

	public $restful = true;
	public $post_data = array();
	public $location_data = array();
	public $category_data = array();

	public $POSTID;


	public function __construct()
	{
		parent::__construct();
		//--Your Code --//
		$this->theme->set_theme("default");
		$this->theme->set_layout("member");

		$this->POSTID = 0;
	}


	public function get_add($step = 1){
		$user = Auth::user();
		$data['title'] = "Add Your Business";
		switch ($step) {
			case 1:
				$data['step'] = $step;
				$data['cat_parent'] = Categories::where('parent_id','=',0)->select(array('id', 'name'))->get();

				$data['title'] = "Add Business";
				$this->theme->title($data['title'].' - '.Settings::get('en','site_title'));
				/*-- BREADCRUMB */
				 
				Breadcrumb::addbreadcrumb('Home', URL::base());
				Breadcrumb::addbreadcrumb('Member', URL::base().'/member');
				Breadcrumb::addbreadcrumb('Add Business', URL::base());
				Breadcrumb::setSeparator('&raquo;');
				$data['breadcrumb'] = Breadcrumb::generate();
				return $this->theme->render('member::post.add1', $data);
				break;

			case 2:

				$data['step'] = $step;
				if(!Session::get('POSTID'))
				{
					return Redirect::to(URL::base().'/member/post/add/1');
				}
				$postID = Session::get('POSTID');

				 
				/*-- POPULATED KEYWORD ---*/
				$last_cat = Terms::category($postID, true);
				$data['keyword'] = Hierarchy::get_descendents('categories',$last_cat);
				$data['keyID'] = Terms::category($postID, true);
				$data['title'] = "Add Business";
				$this->theme->title($data['title'].' - '.Settings::get('en','site_title'));
				/*-- BREADCRUMB */
				 
				Breadcrumb::addbreadcrumb('Home', URL::base());
				Breadcrumb::addbreadcrumb('Member', URL::base().'/member');
				Breadcrumb::addbreadcrumb('Add Business', URL::base());
				Breadcrumb::setSeparator('&raquo;');
				$data['breadcrumb'] = Breadcrumb::generate();
				return $this->theme->render('member::post.add2', $data);
				break;

			case 3:

				$postID = Session::get('POSTID');
				$term_loc = Terms::location($postID, false);
				$l ='';
				foreach($term_loc as $tl){
					$l .= Locations::find($tl->value)->name.',';
				}
				$post = Post::find($postID);
				$address1 = $post->address1;
				$address2 = ($post->address2 != '' ? ', '.$post->address2 : '');
				$l = $address1.$address2.','.$l;
				 
				$Gmap = new Gmaps();
				$config = array();
				$config['center'] = $l;

				 


				$config['onboundschanged'] = 'if (!centreGot) {
				var mapCentre = map.getCenter();
				marker_0.setOptions({
				position: new google.maps.LatLng(mapCentre.lat(), mapCentre.lng())
		});
		}
		centreGot = true;';

				$config['zoom'] = '12';
				$Gmap->initialize($config);

				$marker = array();
				$marker['draggable'] = true;
				//$marker['ondragend'] = 'alert(\'You just dropped me at: \' + event.latLng.lat() + \', \' + event.latLng.lng());';
				$marker['ondrag'] = 'document.getElementById("lat").value=   + event.latLng.lat()  ; document.getElementById("long").value=   + event.latLng.lng()  ; ' ;

				$Gmap->add_marker($marker);
				$data['map'] = $Gmap->create_map();

				//	dd($data['map']);

				$data['step'] = $step;
				$data['center'] =  $config['center'];


				$data['title'] = "Add Business";
				$this->theme->title($data['title'].' - '.Settings::get('en','site_title'));
				/*-- BREADCRUMB */
				 
				Breadcrumb::addbreadcrumb('Home', URL::base());
				Breadcrumb::addbreadcrumb('Member', URL::base().'/member');
				Breadcrumb::addbreadcrumb('Add Business', URL::base());
				Breadcrumb::setSeparator('&raquo;');
				$data['breadcrumb'] = Breadcrumb::generate();

				return $this->theme->render('member::post.add3', $data);
				break;
		}



	}

	public function post_add($step = 1){
		$user = Auth::user();

		switch ($step) {
			case 1:
				//dd($ka);

				$rules = array(
				'title' => 'required|min:5',
				'category' => 'required',
				'keywords' => 'required',
				'street' => 'required',
				'selectbox-mylocation' => 'required',
				);

				$validator = Validator::make(Input::get(), $rules);

				if( $validator->fails() )
				{
					return Redirect::back()->with_input()->with_errors($validator)->with('message','Invalid Operation !');
				}
				else
				{
					$this->post_data = array(
							'users_id' => $user->id,
							'title' => Input::get('title'),
							'slug' => Str::slug(Input::get('title')),
							'meta_title' => Input::get('title'),
							'meta_keyword' => Input::get('title'),
							'meta_description' =>Input::get('title'),
							'address1' => Input::get('street'),
							'address2' => Input::get('address2'),
							'zip_code' => Input::get('zip'),
							'created_at' => Commoncall::current_timestamp(),
							'updated_at' => Commoncall::current_timestamp(),
					);

					// Prepare Category
					$cat = Hierarchy::get_ancestors('categories',Input::get('category'));
					$cat_array = array();
					foreach($cat as $c){
						$cat_array[] = $c->id;
					}
					$this->category_data = $cat_array;



					// Prepare Location
					$loc = Hierarchy::get_ancestors('locations',Input::get('selectbox-mylocation'));
					$loc_array = array();
					foreach($loc as $l){
						$loc_array[] = $l->id;
					}
					$this->location_data = $loc_array;

					/*--INSERT INTO POST --*/
					$this->POSTID = DB::table('post')->insert_get_id($this->post_data);

					Session::put('POSTID',$this->POSTID);

					/*--INSERT TERM (CATEGORY) --*/
					foreach($this->category_data as $cat){
						$cat_data = array(
								'post_id' => $this->POSTID,
								'term' => 'category',
								'caption' => 'Category',
								'value' => $cat
						);

						DB::table('terms')->insert($cat_data);
					}


					/*--INSERT TERM (KEYWORD) --*/
					$ka = Input::get('keywords');

					foreach($ka as $value){
						$key_data = array(
								'post_id' => $this->POSTID,
								'term' => 'keyword',
								'caption' => 'Keyword',
								'value' => $value
						);
						DB::table('terms')->insert($key_data);
					}

					/*--INSERT TERM (LOCATION) --*/
					foreach($this->location_data as $loc){
						$loc_data = array(
								'post_id' => $this->POSTID,
								'term' => 'location',
								'caption' => 'Location',
								'value' => $loc
						);

						DB::table('terms')->insert($loc_data);
					}
				}
				/*-- REDIRECT TO PAGE 2 */
				return Redirect::to(URL::base().'/member/post/add/2');
				break;

			case 2:

				$rules = array(
				'phone1' => 'required',
				'email' => 'required|email',
				'website' => 'url|active_url',
				'description' => 'required',


				);
				$validator = Validator::make(Input::get(), $rules);
				if( $validator->fails() )
				{
					return Redirect::back()->with_input()->with_errors($validator)->with('message','Invalid Operation !');
				}
				else
				{
					$filename = Input::file('image.name');
					if($filename == TRUE){
					
						
					$extension = File::extension($filename);
					$image = Input::file('image');
					$dirPath = path('storage').'uploads/logos/';
					$filename = $image['name'];
					 
					//	if($filename == FALSE){
					//	$filename = 'no-logo.jpg';
					//	}
					 
					$createFolders = true;
					$backgroundColor = null;
					$imageQuality = 100;
					 
					//--NEW NAME --//
					$filename = md5($filename).'.'.$extension;
					 
					$layer = PHPImageWorkshop\ImageWorkshop::initFromPath($image['tmp_name']);
					 
					$thumbWidth = 300; // px
					$thumbHeight = 250;
					$conserveProportion = false;
					$positionX = 0; // px
					$positionY = 0; // px
					$position = 'LT';
					 
					$layer->resizeInPixel($thumbWidth, $thumbHeight, $conserveProportion, $positionX, $positionY, $position);
					$layer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);
					 
					 
					$postID = Session::get('POSTID');
					
						$post_data = array(
								'phone1'    => Input::get('phone1'),
								'phone2'    => Input::get('phone2'),
								'email'     => Input::get('email'),
								'website'    => Input::get('website'),
								'fax'       => Input::get('fax'),
								'tollfree'  => Input::get('tollfree'),

								'contact_name'  => Input::get('contact_name'),
								'contact_name2'  => Input::get('contact_name2'),
								'contact_no'  => Input::get('contact_no'),
								'contact_no2'  => Input::get('contact_no2'),

								'description'       => Input::get('description'),
								'services'  => Input::get('services'),
								'logo' => $filename,
						);
					}else{
						$postID = Session::get('POSTID');
					
						$post_data = array(
								'phone1'    => Input::get('phone1'),
								'phone2'    => Input::get('phone2'),
								'email'     => Input::get('email'),
								'website'    => Input::get('website'),
								'fax'       => Input::get('fax'),
								'tollfree'  => Input::get('tollfree'),
								 
								'contact_name'  => Input::get('contact_name'),
								'contact_name2'  => Input::get('contact_name2'),
								'contact_no'  => Input::get('contact_no'),
								'contact_no2'  => Input::get('contact_no2'),
								 
								'description'       => Input::get('description'),
								'services'  => Input::get('services'),
								 
						);
					}
					DB::table('post')->where('id', '=',$postID)
					->update($post_data);

				}

				/*-- REDIRECT TO PAGE 3 */
				return Redirect::to(URL::base().'/member/post/add/3');
				break;

			case 3:
				
				$rules = array(
						'long' => 'required',
						'lat'	=> 'required',
				
				);
				$validator = Validator::make(Input::get(), $rules);
				if( $validator->fails() )
				{
					return Redirect::back()->with_input()->with_errors($validator)->with('message','<div class="alert alert-danger">Please Drag the pointer and set your location</div>');
				}else{

				$postID = Session::get('POSTID');
				$post_data = array(
						'long'    => Input::get('long'),
						'lat'    => Input::get('lat'),
						'status' => '1',
				);
				}
				DB::table('post')->where('id', '=', $postID)
				->update($post_data);

				return Redirect::to('/member');
				break;



		} /* END CASE */
	}

	
	public function get_delete($pID){
		 
		DB::table('post')->where('id','=',$pID)->delete();

		DB::table('terms')->where('post_id','=',$pID)->delete();
		
		return Redirect::back();
	}

	 
	public function get_photo($pID){
		 
		$data['mode'] = "PHOTO";
		$data['postID'] = $pID;
		 
		$data['photo'] = DB::table('gallery')->where('post_id','=',$pID)->where('term','=','photo')->get();
		 
		$data['title'] = "Add Photo";

		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb('Member', URL::base().'/member');
		Breadcrumb::addbreadcrumb('Add Business', URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();
		return $this->theme->render('member::post.gallery',$data);
		 
	}

	public function post_photo(){


		$filename = Input::file('image.name');
		$extension = File::extension($filename);
		$image = Input::file('image');
		$dirPath = path('storage').'uploads/photos/';
		$filename = $image['name'];

		if($filename == FALSE){
			return Redirect::back()->with('message','<div class="alert alert-warning">Browse filed can not be null..</div>');
		}

		$createFolders = true;
		$backgroundColor = null;
		$imageQuality = 100;

		//--NEW NAME --//
		$filename = md5($filename).'.'.$extension;

		$layer = PHPImageWorkshop\ImageWorkshop::initFromPath($image['tmp_name']);

		$thumbWidth = 300; // px
		$thumbHeight = 250;
		$conserveProportion = false;
		$positionX = 0; // px
		$positionY = 0; // px
		$position = 'LT';

		$layer->resizeInPixel($thumbWidth, $thumbHeight, $conserveProportion, $positionX, $positionY, $position);
		$layer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);

		$post_data = array(
				'value' => $filename,
				'post_id' => Input::get('pID'),
				'term' => 'photo',
				'caption' => 'Photo',
				'status' => '1'
				 
		);

		DB::table('gallery')->insert($post_data);
		return Redirect::back()->with('message','<div class="alert alert-info">Data Successfully added !</div>');
	}


	public function get_video($pID){

		$data['mode']= "VIDEO";
		$data['postID'] = $pID;
		 
		$data['title'] = "Add Video";

		$data['video'] = DB::table('gallery')->where('post_id','=',$pID)->where('term','=','video')->get();
		 

		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb('Member', URL::base().'/member');
		Breadcrumb::addbreadcrumb('Add Business', URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();
		return $this->theme->render('member::post.gallery',$data);
	}
	 
	public function post_video(){

		$video = Input::get('video_link');
		$postID = Input::get('pID');

		if($video == FALSE){
			return Redirect::back()->with('message','<div class="alert alert-warning">Video link field can not be null</div>');
		}

		$len=strlen($video);
		$pos=strrpos($video, '=');
		$urlid= substr($video,$pos+1);


		$post_data = array(
				'value' => $urlid,
				'post_id' => Input::get('pID'),
				'term' => 'video',
				'caption' => 'Video',
				'status' => '1'
					
		);

		DB::table('gallery')->insert($post_data);
		return Redirect::back()->with('message','<div class="alert alert-info">Data Successfully added !</div>');
	}
	 
	 
}